<template>
  <div id="editorCom">
    <textarea :id="id"></textarea>
  </div>
</template>
<script>
import tinymce from 'tinymce'
// import 'tinymce/icons/default/icons.min.js'
import 'tinymce/skins/ui/oxide/skin.min.css'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/image'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/code'
import 'tinymce/plugins/fullpage'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/link'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/toc'

export default {
  name: 'richEditor',
  data() {
    return {
      flag: true,
    }
  },
  watch: {
    value(val) {
      if (this.flag) {
        this.setContent(val)
      }
      this.flag = true
    },
  },
  methods: {
    goEnd() {
      let editor = tinymce.editors[this.id]
      editor.execCommand('selectAll')
      editor.selection.getRng().collapse(false)
      editor.focus(false)
    },
    initEditor() {
      tinymce.init(this.option)
    },
    // 获取内容
    getContent() {
      return tinymce.editors[this.id].getContent()
    },
    // 设置内容
    setContent(content) {
      tinymce.editors[this.id] && tinymce.editors[this.id].setContent(content)
    },
    // 插入内容
    addHtml(val) {
      tinymce.editors[this.id]
        ? tinymce.editors[this.id].insertContent(val)
        : console.error('编辑器初始化失败')
    },
    // 覆盖填充富文本编辑器的内容Z
    changeContent(content) {
      tinymce.editors[this.id]
        ? tinymce.editors[this.id].setContent(content)
        : console.error('编辑器初始化失败')
    },
    destory() {
      tinymce.editors[this.id] && tinymce.editors[this.id].destroy()
    },
  },
  props: {
    // id
    min_height: {
      type: Number,
      default: 600,
    },
    value: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: 'editor' + Date.now(),
    },
    pasteDataImages: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: String,
      default:
        'emoticons paste fullpage charmap advlist autolink link image imagetools lists preview  media searchreplace table code autoresize toc',
    },
    toolbarSticky: {
      type: Boolean,
      default: false,
    },
    toolbar: {
      type: [Array, String],
      default: function () {
        return 'undo redo forecolor backcolor bold italic underline strikethrough link  removeformat | fontsizeselect styleselect   indent outdent alignleft aligncenter alignright alignjustify bullist numlist table emoticons preview image fullpage charmap media blockquote selectall searchreplace imagetool toc'
      },
    },
    imagesUploadUrl: {
      type: String,
    },
    imagetoolsCorsHosts: {
      type: Array,
      default: function () {
        return []
      },
    },
    emoticons_database_url: {
      type: String,
      default: 'https://nb-oa-web.lianlianlvyou.com/static/plugins/emojis.js',
    },
    // 组件可以通过传递一个prop----handlerImageUpload方法来自定义上传图片
    handlerImageUpload: {
      // 接收三个参数 blobInfo, 类似用法如下
      // let formData = new FormData()
      // formData.append('file', blobInfo.blob(), blobInfo.filename())
      // success 成功时候的回调函数 需要传入文件上传后的地址
      // failure 文件失败后的回调函数 传入用于提示的信息
      type: Function,
    },
    // 有插件默认配置项
    option: {
      type: Object,
      default: function () {
        let id = this.id,
          plugins = this.plugins,
          toolbar = this.toolbar,
          images_upload_url = this.imagesUploadUrl,
          handlerImageUpload = this.handlerImageUpload,
          placeholder = this.$attrs.placeholder,
          toolbarSticky = this.toolbarSticky,
          pasteDataImages = this.pasteDataImages
        return {
          // 选择配置器
          selector: '#' + id,
          // 插件配置
          plugins,
          emoticons_database_url: this.emoticons_database_url,
          // 汉化语言包(需要先下载资源)
          language: 'zh_CN',
          // 禁止粘贴base64格式的图片
          paste_data_images: pasteDataImages,
          paste_webkit_styles: 'all',
          // 修复复制时换行样式重复问题
          // paste_preprocess:function(plugin, args){
          //   console.log(args.content)
          //   if(args.content&&!args.content.endsWith('<p>&nbsp;</p>')){
          //     args.content = args.content+'<p></p>'
          //   }
          // },
          min_height: this.min_height,
          relative_urls: false,
          language_url:
            'https://oa-app-web.lianlianlvyou.com/js/tiny_locale_zh_CN.js',
          content_style: 'img{max-width:100%}',
          content_css: [
            'https://oa-app-web.lianlianlvyou.com/css/tiny_mce_content.min.css',
            'https://oa-app-web.lianlianlvyou.com/css/tiny_mce_default_content.css',
          ],
          toolbar,
          // 允许自定义添加图片的样式
          image_advtab: true,
          toolbar_mode: 'sliding',
          imagetools_cors_hosts: this.imagetoolsCorsHosts,
          // 上传图片的地址 自动转base64到img标签
          images_upload_url,
          images_upload_handler: handlerImageUpload ? handlerImageUpload : null,
          // 自动获取焦点
          auto_focus: false,
          placeholder: placeholder,
          // 图片标题
          image_caption: true,
          // 文件编码
          fullpage_default_encoding: 'UTF-8',
          // 可调节高度大小
          // resize: false,
          // dom状态栏
          statusbar: false,
          toolbar_sticky: toolbarSticky,
          setup: editor => {
            editor.on('init', () => {
              if (this.value) {
                editor.setContent(this.value)
              }
              // 抛出 'on-ready' 事件钩子
              this.$emit('on-ready', 'come from init')
            })
            // 双向数据绑定 ，同步value数据
            editor.on('input undo redo execCommand change', e => {
              // 失去焦点的时候也会触发change事件 但是因为没有改变内容的话不会走watcher 特俗处理一下
              if (e.originalEvent && e.originalEvent.type === 'blur') {
                this.$emit('input', editor.getContent())
                return
              }
              this.flag = false
              this.$emit('input', editor.getContent())
            })
            // 实现拖拽网页复制
            editor.on('dragover', event => {
              event.preventDefault()
            })
            // 修复插入内容换行样式重复
            editor.on('BeforeSetContent', event => {
              if (
                event.content.endsWith('<p> </p>') ||
                event.content.endsWith('<p></p>')
              ) {
                return
              }
              if (event.content && /^<(div|section)/.test(event.content)) {
                event.content = event.content + '<p></p>'
              }
            })
            editor.on('drop', event => {
              event.preventDefault()
              let data = event.dataTransfer.getData('text/plain')
              data = data.replace(
                /(draggable="true")|(draggable='true')|draggable/g,
                ''
              )
              editor.insertContent(data)
            })
          },
        }
      },
    },
  },
  mounted() {
    setTimeout(() => {
      this.initEditor()
    }, 100)
    this.$once('hook:beforeDestroy', () => {
      this.destory()
    })
  },
}
</script>
